<?php

namespace App\Model;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;

class Goods extends Model
{
    //
    protected $guarded = [];
    public $timestamps = false;
    protected $table = 'goods';
    protected $good_info = 'goods_info';


    /**
     * 模型的「启动」方法
     *
     * @return void
     */
    protected static function boot()
    {
        parent::boot();

        static::addGlobalScope('exist', function(Builder $builder) {
            $builder->where('is_del', 1);
        });
    }

    /**
     * 通过积分筛选
     * @param $query
     * @param $scores
     * @return mixed
     */
    public function scopeFilterByScores($query, $scores)
    {
        if ($scores) {
            $query = $query->where('scores', $scores);
        }
        return $query;
    }

    /**
     * 通过会员等级条件筛选
     * @param $query
     * @param $level
     * @return mixed
     */
    public function scopeFilterByLevel($query, $level)
    {
        if ($level) {
            $query = $query->whereRaw("FIND_IN_SET(?, allow_level)", [$level]);
        }
        return $query;
    }

    /**
     * 已上架
     * @param $query
     * @return mixed
     */
    public function scopeOnline($query)
    {
        return $query->where('status', 1);
    }

    /*
     * 查询分页
     */
    public function GetGoods($like=null,$status,$page=10,$id=null){
        $data = $this->leftjoin($this->good_info,$this->good_info.'.goods_id','=',$this->getTable().'.id');
            if(!empty($id)){
                    $data = $data->where($this->getTable().'.id',$id);
            }else{
                $data = $data->where(function($query)use($like,$status){
                    if(!empty($like)){
                        $query->where($this->getTable().'.goods_name','like',"%$like%");
                    }
                    if($status!=-1){
                        $query->where($this->getTable().'.status','=',$status);
                    }
                });
            }

        $data = $data->orderBy($this->getTable().'.create_time','desc')->where($this->getTable().'.is_del','=','1')->paginate($page);
        return $data;
    }

}
